package com.linwen.javase.juc;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;


/**
 * @ClassName _14SemaphoreThread
 * @Description
 * @Author lin
 * @Date 2022/4/23 上午12:04
 * @Version V1.0
 *信号灯，设置信号量值，线程进行抢占信号量，若信号量为0 那么线程将等待
 * 线程执行之后，释放信号量，其余线程可抢占
 *
 */
public class _14SemaphoreThread {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();// 抢占信号量
                    System.out.println(Thread.currentThread().getName()+"抢占了车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName()+"-----离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}
